package com.yswee.framework.utils;

import com.yswee.framework.Application;
import com.yswee.framework.widget.MToast;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import androidx.core.content.FileProvider;
import android.text.TextUtils;

import java.io.File;

public class IntentUtils {
	/**
	 * 拨打电话
	 * @param activity
	 * @param tele
	 */
	public static void call(String tele) {
		if (TextUtils.isEmpty(tele)) {
			MToast.showToastMessage("电话号码为空");
		} else {
			try {
				Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tele));
				phoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Application.get().startActivity(phoneIntent);
			} catch (Exception e) {
				StringUtils.copyToClipboard(tele, "拨打电话失败，电话号码已复制到手机粘贴板");
			}
		}
	}
	
	/**
	 * 播放视频
	 */
	public static void playVideo(Context context, Uri uri){
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(uri, "video/*");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addCategory(Intent.CATEGORY_DEFAULT);
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Application.get().startActivity(intent);
		} catch (SecurityException e) {
			if (uri.toString().contains("/storage/emulated/0")) {
				String filepath_tmp = "/storage/emulated/0" + uri.toString().split("/storage/emulated/0")[1];
				uri = FileProvider.getUriForFile(context, PackageUtils.getPackageName(context) + ".fileProvider",
						new File(filepath_tmp));
				playVideo(context, uri);
			}
		} catch (Exception e) {
			MToast.showToastMessage("播放视频失败");
		}
	}

	/**
	 * 播放音频
	 */
	public static void playAudio(Context context, Uri uri) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(uri, "audio/*");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addCategory(Intent.CATEGORY_DEFAULT);
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Application.get().startActivity(intent);
		} catch (SecurityException e) {
			if (uri.toString().contains("/storage/emulated/0")) {
				String filepath_tmp = "/storage/emulated/0" + uri.toString().split("/storage/emulated/0")[1];
				uri = FileProvider.getUriForFile(context, PackageUtils.getPackageName(context) + ".fileProvider",
						new File(filepath_tmp));
				playVideo(context, uri);
			}
		} catch (Exception e) {
			MToast.showToastMessage("播放音频失败");
		}
	}
	
	/**
	 * 转到操作系统设置
	 */
	public static void gotoSetting(Context context) {
		context.startActivity(new Intent(Settings.ACTION_SETTINGS));
	}
	
	/**
	 * 转到操作系统网络设置
	 */
	public static void gotoNetSetting(Context context) {
		context.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
	}
}
